﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.DataModel;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	public class CreatDuctTerminalTag : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			if (commandData == null)
			{
				throw new System.ArgumentNullException();
			}
			UIApplication application = commandData.Application;
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			Autodesk.Revit.DB.View activeView = activeUIDocument.ActiveView;
			Selection selection = activeUIDocument.Selection;
			if (!YJKRevitTools.ViewCheck(activeUIDocument, new List<ViewType>
			{
				(ViewType)1,
				(ViewType)2
			}))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Result result;
			try
			{
				FrmDTerminalMark frmDTerminalMark = new FrmDTerminalMark();
				DialogResult dialogResult = DialogResult.OK;
				do
				{
					if (dialogResult == DialogResult.OK)
					{
						dialogResult = frmDTerminalMark.ShowDialog();
					}
					if (dialogResult == DialogResult.Yes)
					{
						transaction = new Transaction(document, "风口标注");
						transaction.Start();
						new HYTagOperate(commandData).MarkTerminalTag(frmDTerminalMark.isHaveFlow, frmDTerminalMark.bHasPrefix);
						dialogResult = DialogResult.Yes;
						document.Regenerate();
						transaction.Commit();
					}
				}
				while (dialogResult != DialogResult.Cancel);
				frmDTerminalMark.Close();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
					if ((int)status == 1)
					{
						transaction.Commit();
					}
					else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
